<?php
/**
 * $Id: tag.php 31 2010-05-20 06:14:34Z varun $
 * 
 * This file can not be redistributed to anyone without the permission of Giga Promoters
 * Copyright 2005 - 2008, Giga Promoters
 * 						  608 Aggarwal Cyber Plaza
 *						  Netaji Subhash Place, Delhi - 110034
 *						  www.gigapromoters.com
 * 
 *
 * @version 			$Rev: 31 $
 * @lastModifiedBy		$LastChangedBy: varun $
 * @lastChanged			$Date: 2010-05-20 11:44:34 +0530 (Thu, 20 May 2010) $
 * @copyright 			Giga Promoters (www.gigapromoters.com)
 * 
 */

/**
 * Tag Model. Need advanced functions in near future.
 *
 */
class Tag extends TagsAppModel
{
    var $name = 'Tag';
	var $actsAs =  array('Sluggable'=>array('label'=>'tag'));

	function getSimilar($type, $item_id, $count=5)
	{
		$similarItems = array();
		$similarItemsOrdered = array();

		// if cached, then return cached items only
		if($similarItems = @unserialize(cache('similar_'.$type.'_'.$item_id, null)))
		{
			return $this->getItems($similarItems, $count);
		}

		// fetch all tags for given item
		$tags = cri('Tags.TaggedItem')->findAll(array('type'=>$type, 'item_id'=>$item_id), 'tag_id');

		// find videos associated with each tag
		foreach($tags as $tag)
		{
			$tagId = $tag['TaggedItem']['tag_id'];
			$items = cri('Tags.TaggedItem')->findAllbyTag_id($tagId, 'item_id');  // and item_id!=$item_id

			foreach($items as $item)
			{
				$similarItems[] = $item['TaggedItem']['item_id'];
			}
		}

		if(!$similarItems)
		{
			return false;
		}

		// order all similar items, in terms of their occurance
		foreach($similarItems as $item)
		{
			$similarItemsOrdered[$item]++;

		}
		arsort($similarItemsOrdered);
		cache('similar_'.$type.'_'.$item_id, serialize($similarItemsOrdered), '+2 hrs');
		
		return $this->getItems($similarItemsOrdered, $count);
	}

	// to return item_ids
	function getItems($itemIds, $count)
	{
		$i=0;
		$items = array();

		foreach($itemIds as $item_id=>$relevance)
		{
			if($i>=$count)
				break;
			$items[] = $item_id;
			$i++;
		}
		return $items;
	}

	function getTagList($tag,$type)
	{	
		$tagId = $this->field('id',array('slug' =>$tag));
		if(empty($tagId))
		{
			return ;
		}
		$tagName =  $this->field('tag',array('slug' =>$tag));
		$itemList['tagName'] = $tagName;
		$itemList['list'] = classRegistry::init('Tags.TaggedItem')->find('list',array('fields'=>'id,item_id','conditions'=>'tag_id ='.$tagId.' And type ="'.$type.'"'));
		 return $itemList;
	}

	function getTag($list)
	{
		$condition="Tag.id IN(".$list.")";
		$tags = $this->find('all',array('conditions'=>$condition));
		return $tags;
	}
}

?>